<?php

class InboundController extends baseController {
	
	/**
	 * 采购入库
	 */
	public function indent(){
		if(!is_post()){
			/*
			 * 采购订单审核成功、未入库完成的订单；
			 */
			$list = IndentHelper::getList("audit_flow=1 AND back_flow<2");
                        foreach($list as $k=>$v)
                        {
                            $list[$k]['mixvalue'] = $v['sno'].' - '.$v['supplier_name'];
                        }
			$this->assign('list', $list);
                        
			return $this->display();
		}
		
		$indent_id = fetch_a_int('indent_id');
		if(!$indent_id || !Indent::get($indent_id)){
			Show::warn("无此采购订单");
		}
		if(!fetch_a_array('amount')){
			Show::warn("请选择入库的材料");
		}
		if(!fetch_a_int('warehouse_id')){
			Show::warn('请选择仓库');
		}

		$reviewers = array_filter(array_map('intval',fetch_a_array('reviewer')));

		Db::get()->trans()->on();

		$boundid = Bound::add(array(
			'sno'	=> Sno::cgen('inbound'),
			'flow'	=> 0,
			'class'	=> 'in',
			'type'	=> Bound::TYPE_CK,
			'total' => 0.0,
			'addtime' => time(),
			'user_id' => UID,
			'reviewers' => join(',', $reviewers),
			'effect' => 0, #1, //不用通过审核,三方质检只是形式
			'indent_id' => $indent_id,
			'warehouse_id' => fetch_a_int('warehouse_id'),
			'warehouse' => Warehouse::getName(fetch_a_int('warehouse_id')),
		));
		if(!$boundid){
			Show::warn('生成入库记录失败');
		}

		//入库单明细取自采购订单明细
		$indent_items = IndentItems::getByIndent($indent_id);

//		$total = 0.0;
		foreach(fetch_a_array('amount') as $itemid=>$amount){
			if(!isset($indent_items[$itemid])){
				continue;
			}

			$indentItem = $indent_items[$itemid];
			
			if($amount > $indentItem['amount'] - $indentItem['amount_back']){
				Db::get()->trans()->rollback();
				Show::warn("错误：材料\"{$indentItem['name']}\"入库数量大于可入库数量。");
			}
			elseif($amount < 1){
				Db::get()->trans()->rollback();
				Show::warn("错误：材料\"{$indentItem['name']}\"入库数量不能为零。");
			}

//			//更新材料库存价值
//			if(!Ware::renewValues(array('amount'=>$amount,'price'=>$indentItem['price'],'ware_id'=>$itemid), 1, $errmsg)){
//				Db::get()->trans()->rollback();
//				Show::warn("修改结存信息失败：{$indentItem['name']}：$errmsg");
//			}
//			$ware = Ware::getValues($itemid);
//			$total += $ware['total'];

			//保存入库明细
			if(!BoundItems::add(array(
				'bound_id'	=> $boundid,
				'class'		=> 'in',
				'ware_id'	=> $itemid,
				'sno'		=> $indentItem['sno'],
				'name'		=> $indentItem['name'],
				'specific'	=> $indentItem['specific'],
				'unit'		=> $indentItem['unit'],
				'brand'		=> $indentItem['brand'],
				'remark'	=> $indentItem['remark'],
				'amount'	=> $amount,
				'price'		=> $indentItem['price'],
				'total'		=> intval($amount) * $indentItem['price'],
				'effect'	=> 0, #1,
				'addtime'	=> time(),
				'sum_day'	=> date('Ymd'),
//				'bl_amount'	=> $ware['amount'],
//				'bl_price'	=> $ware['price'],
//				'bl_total'	=> $ware['total'],
			))){
				Db::get()->trans()->rollback();
				Show::warn("保存材料\"{$indentItem['name']}\"时出错。");
			}

			/*
			 * 先从采购订单中标记已有部分材料入库，此时并不实际增加库存，只为在做入库单时减少可入库数量；
			 */
			Db::get('IndentItems')->update(array('amount_back'=>$indentItem['amount_back']+$amount))
					->where(array('indent_id'=>$indent_id,'ware_id'=>$itemid))->exec();
			if(!Db::get('IndentItems')->affectedRows()){
				Db::get()->trans()->rollback();
				Show::warn("修改采购订单材料\"{$indentItem['name']}\"状态时出错。");
			}
//
//			//设置需求明细的回库数量，这个是算出来的，而且是按需求ID依次满足
//			$list = Db::get('_DemandItems')->select('t0.demand_id,t0.amount,t0.amount-t0.amount_back as amount_diff')
//					->join('_IndentItems')->on('t1.summary_id=t0.summary_id')
//					->where("t1.indent_id={$indent_id} and t0.ware_id={$itemid} and t1.ware_id={$itemid}")
//					->getAll();
//			$num = $amount;
//			$len = count($list);
//			for($i=0;$i<$len && $num>0;$i++){
//				$_amt = 0;
//				if($num < $list[$i]['amount_diff']){
//					$_amt = $num;
//					$num = 0;
//				}
//				else{
//					$_amt = $list[$i]['amount_diff'];
//					$num -= $list[$i]['amount_diff'];
//				}
//				Db::get('DemandItems')->update("amount_back=amount_back+{$_amt}")
//						->where(array('demand_id'=>$list[$i]['demand_id'], 'ware_id'=>$itemid))->exec();
//			}
				
		} //end of foreach

//		Db::get('Bound')->update(array('total'=>$total))->where(array('id'=>$boundid))->exec();
//		Db::get('Indent')->update(array('back_flow'=>1))->where(array('id'=>$indent_id))->exec();

		//写质检人到reviewer
		foreach($reviewers as $rvid){
			Db::get('Reviewer')->insert(array(
				'class'	=> Reviewer::CLS_QC,
				'related_id' => $boundid,
				'user_id' => $rvid,
//				'track' => UserTrack::get(),
			))->exec();
		}

		Db::get()->trans()->commit();
		Show::note('入库单据创建成功');
	}
	
	/** 通过采购订单编号取明细 */
	public function indent_sno(){
		$sno = fetch_a_string('sno');
		if(!$sno){
			Show::warn('请输入采购订单编号.');
		}
		$indent = Indent::getBySno($sno);
		if(!$indent){
			Show::warn('无此采购订单编号.');
		}
		$indent['items'] = IndentItems::getByIndent($indent['id']);
		$this->assign('indent', $indent);
		
		$indent_users = IndentHelper::getIndentPeople($indent['id']);
//		$demand_users = IndentHelper::getDemandPeople($indent['id']);
		$demand_users = array_diff_key(User::getPureList(), $indent_users, array(UID=>''));
		
		$this->assign('demandReviewers', $demand_users);
		$this->assign('indentReviewers', $indent_users);
//		$this->assign('users', $users);
		
		$this->display();
//		Show::ajaxBand(array('html'=>$this->fetch()));
//		Show::note('ok');
	}
	
	/** 退料入库 */
	public function revert(){
		if(is_post()) { $this->save(Bound::TYPE_TL); }
		$this->display();
	}
	
	/** 工程移交 */
	public function transfer(){
		if(is_post()) { $this->save(Bound::TYPE_YJ); }
		$this->display();
	}
	
	/** 盘盈调入 */
	public function overage(){
		if(is_post()) { $this->save(Bound::TYPE_PY); }
		$this->display();
	}
	
	/** 保存入库信息 */
	protected function save($type){
		if(!fetch_a_int('warehouse_id')){
			Show::warn('请选择仓库');
		}
		
		$amounts = fetch_a_array('amount');
		$remarks = fetch_a_array('remark');
		$prices  = fetch_a_array('price');

		$data	= array();
		$total	= 0.0;
		foreach($amounts as $stuff_id => $amount) {
			if(empty($amount)){
				Show::warn("请填写全部材料的数量");
			}
			$ware = Ware::getbyid($stuff_id);
			if(!$ware){
				Show::warn("无此材料信息");
			}
			$data[$stuff_id] = array(
				'amount'	=> intval($amount),
				'price'		=> floatval($prices[$stuff_id]),
				'remark'	=> FilterHelper::strip(fetch_a_string($stuff_id, $remarks)),
				'id'	=> $ware['id'],
				'name'	=> $ware['name'],
				'sno'	=> $ware['sno'],
				'brand'	=> $ware['brand'],
				'specific' => $ware['specific'],
				'unit'	=> $ware['unit'],
			);
			$total += ($data[$stuff_id]['amount'] * $data[$stuff_id]['price']);
		}

		if($data) {
			Db::get('Bound')->trans()->on();
			
			$boundid = Bound::add(array(
				'sno'	=> Sno::cgen('inbound'),
				'flow'	=> 0,
				'class'	=> 'in',
				'type'	=> $type,
				'total' => $total,
				'addtime' => time(),
				'user_id' => UID,
				'effect' => 1,
				'warehouse_id' => fetch_a_int('warehouse_id'),
				'warehouse' => Warehouse::getName(fetch_a_int('warehouse_id')),
			));
			if(!$boundid){
				Show::warn('生成入库记录失败');
			}
			
			foreach($data as $itemid=>$row){

				//更新材料库存价值
				$ware = Db::get('Ware')->select('amount,price,amount*price AS total')->where(array('id'=>$itemid))->getOne();
				$ware['amount'] += $row['amount'];
				$ware['total']  += intval($row['amount']) * $row['price'];
				$ware['price']  = $ware['total'] / $ware['amount'];
				Db::get('Ware')->update($ware)->where(array('id'=>$itemid))->exec();
				if(!Db::get('Ware')->affectedRows()){
					Db::get()->trans()->rollback();
					Show::warn("修改材料\"{$row['name']}\"的结存信息时出错。");
				}

				//保存入库明细
				if(!BoundItems::add(array(
					'bound_id'	=> $boundid,
					'class'		=> 'in',
					'ware_id'	=> $itemid,
					'sno'		=> $row['sno'],
					'name'		=> $row['name'],
					'specific'	=> $row['specific'],
					'unit'		=> $row['unit'],
					'brand'		=> $row['brand'],
					'remark'	=> $row['remark'],
					'amount'	=> $row['amount'],
					'price'		=> $row['price'],
					'total'		=> intval($row['amount']) * $row['price'],
					'effect'	=> 1,
					'addtime'	=> time(),
					'sum_day'	=> date('Ymd'),
					'bl_amount'	=> $ware['amount'],
					'bl_price'	=> $ware['price'],
					'bl_total'	=> $ware['total'],
				))){
					Db::get()->trans()->rollback();
					Show::warn("保存材料\"{$row['name']}\"时出错。");
				}

			}

			Db::get()->trans()->commit();
			
			Show::note('保存成功');
		}
		else {
			Show::warn('请输入正确的材料信息');
		}
		
	}
	
	public function view(){
		$inbound = BoundHelper::getDetail(fetch_a_int('id'));
		if(!$inbound){
			Show::warn('无此入库记录');
		}
//		Debug::pre($inbound);
		$this->assign('inbound', $inbound);
		$this->assign('reviewers', ReviewerHelper::getList(Reviewer::CLS_QC, fetch_a_int('id')));
//		Debug::pre(ReviewerHelper::getList(Reviewer::CLS_QC, fetch_a_int('id')));
		$this->display();
	}
	
	public function detail(){
		$where = "class='in' AND effect=1";
		
		$from = intval(str_replace('-','',fetch_a_string('from')));
		$to   = intval(str_replace('-','',fetch_a_string('to')));
		if($from || $to){
			if(!$from) $from = '20110101';
			if(!$to) $to = date('Ymd');
			$where .= " AND sum_day >= {$from} AND sum_day <= {$to}";
		}
		if($type=fetch_a_int('type')){
			$where .= " AND type={$type}";
		}
		if($key=fetch_a_string('key')){
			$fields = array('sno','name','specific','unit','brand','remark','bound_sno');
			$GLOBALS['S_KEY'] = $key;
			$func = function($v){ return "`{$v}` LIKE '%{$GLOBALS['S_KEY']}%'"; };
			$where .= (' AND ('. join(' OR ', array_map($func, $fields)). ')');
		}
		
		$page = PagerHelper::split2limit(BoundHelper::getItemsCount($where));
		$list = BoundHelper::getItemsList($where,'',$page[0],$page[1]);
//		Debug::pre($list);
		$this->assign('list', $list);
		$this->assign('types', BoundHelper::getInTypes());
		$this->display();
	}
	
}

?>
